VER="0.1.2"

import network
import urequests
import machine
import bluetooth
import time
import ujson

# 配置 CPU频率
CPU_FREQUENCY = 80000000
machine.freq(CPU_FREQUENCY)


# 初始化 LED
led = machine.Pin(8, machine.Pin.OUT,value=1) # 初始高电平，LED 熄灭

# 连接服务器
def connect_server():
    print(f"Start Try Server: {SERVER_URL}...")
    try:
        response = urequests.get(SERVER_URL)
        print(f"Server Code: {response.status_code}")
        if response.status_code == 200:
            print("server Connect Success，LED OK")
            led.value(0)
            hex_data = response.text
            print(f"From Server Get data: {hex_data}")
            try:
                # 将十六进制数据转换为字节对象
                byte_data = bytes.fromhex(hex_data)
                print("Date TO HEX")
                return byte_data
            except ValueError:
                print("error: data nois HEX")
        else:
            print(f"Server error code: {response.status_code}")
    except Exception as e:
        print(f"server Connect error: {e}")
    finally:
        # 关闭响应对象，释放资源
        if 'response' in locals():
            response.close()
    return None


def setup_bluetooth(byte_data):
    print("Init Bluetooth and broadcast data...")
    ble = bluetooth.BLE()
    ble.active(True)

    adv_data = byte_data
    print("broadcast data...")
    if len(adv_data) <= 31:
        ble.gap_advertise(100, adv_data=adv_data)
        print(f"send broadcast data")
    else:
        print("erroe: broadcast data greater 31")


# print("Program Startup")
# connect_wifi()

if not do_connect():
    print("Wi-Fi 连接失败，程序退出")
else:
    while True:
        print("Program Startup")

        byte_data = connect_server()
        if byte_data:
            setup_bluetooth(byte_data)
        time.sleep(5)
    

